package com.jerry.interceptor;

import com.jerry.token.TokenManager;
import com.jerry.common.constant.Constants;
import com.jerry.token.model.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filename:    UserSecurityInterceptor
 * Description:
 * Copyright:   Copyright (c)2016
 * Company:     lngtop
 *
 * @author: 谢余锋
 * @version: 1.0
 * Create at:   2016/9/8 13:55
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016/9/8      谢余锋        1.0        1.0 Version
 */
public class UserSecurityInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        } else {
            String url = request.getRequestURI();
            if (url.contains("/login")) {
                return true;
            } else {
                response.setHeader("Content-type", "text/html;charset=UTF-8");

                String token = request.getHeader("token");

                TokenModel tokenModel = tokenManager.checkToken(token);
                if (tokenModel == null) {
                    response.setStatus(HttpStatus.UNAUTHORIZED.value());
                    response.getWriter().print("{\"message\":\"<span name='loginRequired'>请重新登录\",\"code\":\"MISSING\"}");
                    return false;
                }
                request.setAttribute(Constants.CURRENT_USER, tokenModel);
                return true;
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }

}
